package com.zw.utils.encrypt;

import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

// RSA 算法类
public class RSAAlgorithm {

    private RSAPublicKey publicKey;
    private RSAPrivateKey privateKey;

    public RSAAlgorithm() {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            keyPairGen.initialize(2048, new SecureRandom());
            KeyPair keyPair = keyPairGen.generateKeyPair();
            publicKey = (RSAPublicKey) keyPair.getPublic();
            privateKey = (RSAPrivateKey) keyPair.getPrivate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // RSA 加密
    public BigInteger rsaEncrypt(BigInteger plaintext) {
        return plaintext.modPow(publicKey.getPublicExponent(), publicKey.getModulus());
    }

    // RSA 解密
    public BigInteger rsaDecrypt(BigInteger ciphertext) {
        return ciphertext.modPow(privateKey.getPrivateExponent(), privateKey.getModulus());
    }

    // RSA 乘法同态
    public BigInteger rsaMultiplyHomomorphic(BigInteger ciphertext1, BigInteger ciphertext2) {
        return ciphertext1.multiply(ciphertext2).mod(publicKey.getModulus());
    }
}
